package com.longxi.tianjintianbao.ui.presenter.patrol;

import android.content.Intent;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataPatrolController;
import com.longxi.tianjintianbao.greedao.entity.Patrol;
import com.longxi.tianjintianbao.greedao.entity.PatrolContent;
import com.longxi.tianjintianbao.listener.SelectPatrolListener;
import com.longxi.tianjintianbao.ui.activity.patrol.PatrolDetailActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.patrol.PatrolListViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.base.LazyFragment;
import com.longxi.tianjintianbao.ui.view.patrol.IPatrolListFgView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NetUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PatrolListFgPresenter extends BasePresenter<IPatrolListFgView> {

    private MultiTypeAdapter adapter;
    private Items items = new Items();
    private String state = "";

    public PatrolListFgPresenter(BaseActivity context, LazyFragment fragment) {
        super(context, fragment);
    }

    public void initAdapter(String state){
        this.state = state;
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(Patrol.class, new PatrolListViewBinder(listener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void getInspectionList(int page, String state){
        if(!NetUtils.isNetworkAvailable(mContext)){
            getData(page, state);
            return;
        }

        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getInspectionList(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Patrol>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<Patrol> result) {
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    mFragment.showNoData();
                    return;
                }

                long userid = MyApplication.loginUser.userid;
                long iptype = Long.parseLong(MyApplication.IPID);

                for (Patrol patrol : result.getData()) {
                    patrol.setUserid(userid);
                    patrol.setIptype(iptype);
                    patrol.setIsDraft("0");
                    long l = DataPatrolController.insertPatrol(patrol);
                    LogUtils.d("patrol", l + patrol.getAddress());
                    if(l != 0){
                        for (PatrolContent patrolContent : patrol.getContent()) {
                            long l2 = DataPatrolController.insertPatrolContent(patrol, patrolContent);
                            LogUtils.d("patrol", l2 + patrolContent.getItem());
                        }
                    }
                }
                getData(page, state);
            }
        });
    }

    /**
     * 测试数据
     */
    public void getData(int page, String state){
        List<Patrol> patrols = new ArrayList<>();
        switch (state) {
            case "0":
                patrols = DataPatrolController.SelectByStartDate(page, 10, state);
                break;
            case "1":
                patrols = DataPatrolController.SearchPatrol(page, 10, state);
                break;
            case "2":
                patrols = DataPatrolController.SearchPatrol(page, 10, state);
                break;
            case "3":
                patrols = DataPatrolController.SelectByEnddatetime(page, 10, "0");
                break;
        }

        if(getView().getRefreshLayout().isRefreshing()){
            items = new Items();
            getView().getRefreshLayout().finishRefresh();//传入false表示刷新失败
        }
        if(getView().getRefreshLayout().isLoading()){
            getView().getRefreshLayout().finishLoadMore();//传入false表示加载失败
        }

        if(page == 0){
            items = new Items();
        }

        if(items.size() == 0 && patrols.size() == 0 ){
            mFragment.showNoData();
        }else if(patrols.size() ==0){
            MyUtils.showToast("没有更多数据");
        }else{
            mFragment.hideLoading();
            items.addAll(patrols);
            adapter.setItems(items);
            adapter.notifyDataSetChanged();
        }

    }

    public void gjstatejz(int page, String state) {
        switch (state) {
            case "0":
                getInspectionList(page, state);
                break;
            case "1":
                getData(page, state);
                break;
            case "2":
                getData(page, state);
                break;
            case "3":
                getData(page, state);
                break;
        }
    }

    SelectPatrolListener listener = new SelectPatrolListener() {
        @Override
        public void onSuccess(Patrol patrol) {
            Intent mainIntent = new Intent(mContext, PatrolDetailActivity.class);
            mainIntent.putExtra(AppConst.BILLID, patrol.getBillid());
            mainIntent.putExtra(AppConst.ISDRAFT, state);
            mainIntent.putExtra(AppConst.ISSCAN, false);
            mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_PATROL_DETAIL);
        }
    };

    public void onDestroy() {
        listener = null;
    }
}
